/**
  ****************************(C) COPYRIGHT 2023 Polarbear*************************
  * @file       usb_task.c/h
  * @brief      usb outputs the IMU and gimbal data to the miniPC
  * @note
  * @history
  *  Version    Date            Author          Modification
  *  V1.0.0     2023-7-11       Penguin         1. done
  *  V1.0.1     Oct-31-2023     LihanChen       1. 完成核心框架的构建，使其与调试模式和 miniPC 模式兼容。
  *  V1.0.2     Nov-1-2023      LihanChen       1. 将 Append_CRC16_Check_Sum_SendPacketVision() 和 Append_CRC-16_Check_Stum_OutputPCData() 合并到 Append_CRC16_Check_Sum() 中
  *  v2.0.0     Feb-24-2024     LihanChen       1. 重构代码，将 usb_task 的发送和接收分离，并实现分包发送和接收视觉和导航数据
  *  v2.0.1     Dec-25-2024     HaoyangZhang    1. 重构代码，删除不必要变量，去除自瞄部分移交算法
  *
  @verbatim
  =================================================================================

  =================================================================================
  @endverbatim
  ****************************(C) COPYRIGHT 2023 Polarbear*************************
*/

#include "minipc.hpp"
#include "referee.hpp"

// External Variable Declarations
rt_thread_t usb_thread;						//Minipc接收线程
static uint8_t MiniPC_State_Vision, MiniPC_State_Twist;
// Variable Declarations
static uint8_t usb_tx_buf[APP_TX_DATA_SIZE];
static uint8_t usb_rx_buf[APP_RX_DATA_SIZE];
static uint8_t USB_RECEIVE_STATE;
//static uint8_t USB_SEND_STATE;
float gyro[3];
extern uint8_t fire;
/**
 * @brief Minipc初始化函数
 *
 */
void Minipc_init(void)
{
//	usb_receive_data.vison_pitch = 0;
//	usb_receive_data.vison_yaw = 0;
	usb_receive_data.vison[0] = 0;//vison_shoot_state
	usb_receive_data.vison[1] = 0;//change_pit
	usb_receive_data.vison[2] = 0;//change_yaw
	usb_receive_data.ros_x = 0;
	usb_receive_data.ros_angular = 0;
	usb_receive_data.ros_spinning_flag = 0;
	
	usb_thread = rt_thread_create("minipc", minipc_thread_entry, RT_NULL, 1024, 8, 10);
    rt_thread_startup(usb_thread);
}

/**
  * @brief      USB任务主函数，switch中为发送，接收部分在usb_receive()中处理
  * @param[in]  argument: 任务参数
  * @retval     None
  */
static void minipc_thread_entry(void *parameter)
{
	while (1)
	{
		MiniPC_State_Vision = MINIPC_LOST;//由于usb接收是阻塞式接收，故此处赋初始值为断线，后在确定连上后状态改变
//		MiniPC_State_Twist = MINIPC_LOST;
		usb_receive();
		usb_send_vision();
//		usb_send_Twist();

		rt_thread_mdelay(10);
	}
}
/*PC接收的接口函数*/
uint8_t MiniPC_Receive_Vision(float *pitch_error, float *yaw_error)
{
	if (MiniPC_State_Vision == MINIPC_LOST)
	{
		*pitch_error = 0.0f;//没有接收到数据时不动
		*yaw_error = 0.0f;
//		minipc_behavior_t.plunk_state = 0;
//		set_current(0);
		return MINIPC_LOST;
	}
	else
	{
		*yaw_error = usb_receive_data.vison[2];
		*pitch_error = usb_receive_data.vison[1];// - gimbal.get_shoot();
//		minipc_behavior_t.plunk_state = 1;
		return MINIPC_ONLINE;
	}
}
/*PC接收的接口函数*/
uint8_t MiniPC_Receive_Twist(float *ros_x_speed, float *ros_angular_speed, uint8_t *spinning_flag)
{
	if (MiniPC_State_Twist == MINIPC_LOST)
	{
		*ros_x_speed = 0.0f;//没有接收到数据时不动
		*ros_angular_speed = 0.0f;
		*spinning_flag = 0.0f;
		return MINIPC_LOST;
	}
	else
	{
		*ros_x_speed = usb_receive_data.ros_x;
		*ros_angular_speed = usb_receive_data.ros_angular;
		*spinning_flag = usb_receive_data.ros_spinning_flag;
		return MINIPC_ONLINE;
	}
}
/**
  * @brief      USB接收主函数，处理接收到的原始数据，根据数据头判断数据类型并分包处理
  * @param      None
  * @retval     None
  */
static void usb_receive
(void)
{
	uint32_t len = USB_RECEIVE_LEN;
	CDC_Receive_FS(usb_rx_buf, &len); // Read data into the buffer

	switch (usb_rx_buf[0])
	{
		case EXPECTED_INPUT_NAVIGATION_HEDER:
			/* 导航 */
			USB_RECEIVE_STATE = RECEIVE_NAVIGATION_STATE;
			memcpy(&ReceivedPacketTwist, usb_rx_buf, sizeof(ReceivedPacketTwist_s));
			usb_receive_navigation(&ReceivedPacketTwist, &usb_receive_data);
			// usb_printf("Receive navigation mode\n");
		break;

		case EXPECTED_INPUT_VISION_HEDER:
		/* 自瞄 */

			USB_RECEIVE_STATE = RECEIVE_VISION_STATE;
//			USB_SEND_STATE = OUTPUT_VISION_STATE;
			memcpy(&ReceivedPacketVision, usb_rx_buf, sizeof(ReceivedPacketVision_s));
			usb_receive_vision(&ReceivedPacketVision, &usb_receive_data);
		
		break;

		default:
			USB_RECEIVE_STATE = USB_STATE_INVALID;
		break;
	  }	memset(usb_rx_buf, 0, sizeof(usb_rx_buf));
}

/**
  * @brief      为视觉部分发送数据
  * @param      None
  * @retval     None
  */
static void usb_send_vision(void)
{
	imu.read_gyro(gyro);  

	SendPacketVision.header = SET_OUTPUT_VISION_HEDER;
  if (game_robot_status.robot_id > 100)//自己为蓝方
	{SendPacketVision.detect_color = 0;}//ReceivedPacketVision.detect_color;   TODO: 由裁判系统赋值，0-Red, 1-Blue(对面机器人)
	else
	{SendPacketVision.detect_color = 1;}
//	SendPacketVision.detect_color = 1;
	SendPacketVision.task_mode = 0;
	SendPacketVision.is_play = 1;
	SendPacketVision.change_target = 0;
	SendPacketVision.reserved = 0; // 保留位，无用
	SendPacketVision.roll = 0;
	SendPacketVision.pitch =0;//;//(SHOOT_ZERO_DEGREE - gimbal.get_shoot() ) * 2 * PI / 8192.0f;
	SendPacketVision.yaw = 0;////((gimbal.get_yaw() - Zero_yaw) % 8192) * 2 * PI / 8192.0f;//imu.read_yaw() * PI / 180.0f;//
	SendPacketVision.aim_x = 1.0f;
	SendPacketVision.aim_y = 2.0f;	
	SendPacketVision.aim_z = 3.0f;
	SendPacketVision.game_time = 300;
	SendPacketVision.timestamp = 0;
	//rt_kprintf("read_yaw:%f\n", ((gimbal.get_yaw() - YAW_ZERO_DEGREE) % 8192) * 2 * PI / 8192.0f);
	Append_CRC16_Check_Sum(&SendPacketVision, sizeof(SendPacketVision_s), 0);
	memcpy(usb_tx_buf, (uint8_t *)&SendPacketVision, sizeof(SendPacketVision_s));
	CDC_Transmit_FS(usb_tx_buf, sizeof(SendPacketVision_s));
}

/**
  * @brief      为导航部分发送数据
  * @param      None
  * @retval     None
  */
static void usb_send_Twist(void)
{
	SendPacketTwist.header = SET_OUTPUT_NAVIGATION_HEDER;
//	SendPacketTwist.behavior_chassis_vx = chassis.get_x_speed();//实际底盘的x方向运动速度 单位m/s
//	SendPacketTwist.behavior_chassis_vy = chassis.get_y_speed();//实际底盘的y方向运动速度 单位m/s
//	
	Append_CRC16_Check_Sum(&SendPacketTwist, sizeof(SendPacketTwist_s), 0);
	memcpy(usb_tx_buf, (uint8_t *)&SendPacketTwist, sizeof(SendPacketTwist_s));
	CDC_Transmit_FS(usb_tx_buf, sizeof(SendPacketTwist_s));
}

/**
  * @brief      接收导航数据
  * @param[in]  ReceivedPacketTwist: USB接收到的导航数据
  *             右手系，x轴向前，y轴向左，z轴向上
  *             - x: x轴方向的线速度，单位为m/s
  *             - y: y轴方向的线速度，单位为m/s
  *             - z: z轴方向的线速度，单位为m/s，置零
  *             - roll: 绕x轴的角速度，单位为rad/s，置零
  *             - pitch: 绕y轴的角速度，单位为rad/s，置零
  *             - yaw: 绕z轴的角速度，单位为rad/s
  * @retval     None
  */
static void usb_receive_navigation(ReceivedPacketTwist_s *ReceivedPacketTwist, USBReceiveData *usb_receive_data)
{
	uint8_t crc_ok = Verify_CRC16_Check_Sum((const uint8_t *)ReceivedPacketTwist, sizeof(ReceivedPacketTwist_s));
	if (crc_ok)
	{
		MiniPC_State_Twist = MINIPC_ONLINE;
		usb_receive_data->ros_x = ReceivedPacketTwist->speed_x;
		usb_receive_data->ros_angular = ReceivedPacketTwist->angular;
		usb_receive_data->ros_spinning_flag = ReceivedPacketTwist->spinning_flag;
		
//		rt_kprintf("ros_x:%f\n", usb_receive_data->ros_x);
//		rt_kprintf("ros_y:%f\n", usb_receive_data->ros_y);
//		rt_kprintf("ros_spinning_flag:%d\n", usb_receive_data->ros_spinning_flag);
	}
}

/**
  * @brief      接收视觉数据
  * @param[in]  ReceivedPacketVision: USB接收到的视觉数据
  * @retval     None
  */
static void usb_receive_vision(ReceivedPacketVision_s *ReceivedPacketVision, USBReceiveData *usb_receive_data)
{
	float pitch=0,yaw=0;
	uint8_t crc_ok = Verify_CRC16_Check_Sum((const uint8_t *)ReceivedPacketVision, sizeof(ReceivedPacketVision_s));//sizeof(ReceivedPacketVision_s)
	if (crc_ok)
	{
		MiniPC_State_Vision = MINIPC_ONLINE;
		//视觉数据处理
//		usb_receive_data->state = ReceivedPacketVision->state;
//		usb_receive_data->vison_pitch = ReceivedPacketVision->change_pitch;
//		usb_receive_data->vison_yaw = ReceivedPacketVision->change_yaw;
//		usb_receive_data->fire = ReceivedPacketVision->fire;
		fire = ReceivedPacketVision->fire;
		usb_receive_data->vison[1] = ReceivedPacketVision->change_pitch;
		usb_receive_data->vison[2]= ReceivedPacketVision->change_yaw;
		
		//rt_kprintf("vison_shoot_state:%d\n", usb_receive_data->fire);
	//	rt_kprintf("vison_pitch:%f\n", usb_receive_data->vison[1]);
	//	rt_kprintf("vison_yaw:%f\n", usb_receive_data->vison[2]);

//		if(ReceivedPacketVision->tracking == 1)
//		{
//			MiniPC_State = MINIPC_ONLINE;
//			usb_receive_data.pitch  = -(pitch * 8192 / (2 * PI));
//			
//			BOUNDARY_PROCESS(usb_receive_data.yaw ,(8192 * fmod(yaw + 2 * PI, 2 * PI)) / (2 * PI)-gimbal.get_yaw(),0.0 ,8192);//边界处理
//			rt_kprintf("%d,%f %d,%f\n",gimbal.get_shoot(),pitch,gimbal.get_yaw(),usb_receive_data.yaw);//SendPacketVision.pitch, SendPacketVision.yaw);
//		}

	}
}

// CRC Table
const uint16_t W_CRC_TABLE[256] = {
  0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3,
  0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
  0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399,
  0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
  0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 0xbdcb, 0xac42, 0x9ed9, 0x8f50,
  0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
  0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e,
  0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
  0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5,
  0xa96a, 0xb8e3, 0x8a78, 0x9bf1, 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
  0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693,
  0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
  0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, 0x3bd3, 0x2a5a,
  0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
  0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710,
  0xf3af, 0xe226, 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
  0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df,
  0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
  0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, 0xe70e, 0xf687, 0xc41c, 0xd595,
  0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
  0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c,
  0x3de3, 0x2c6a, 0x1ef1, 0x0f78};

/**
 * @brief CRC16 Caculation function
 * @param[in] pchMessage : Data to Verify,
 * @param[in] dwLength : Stream length = Data + checksum
 * @param[in] wCRC : CRC16 init value(default : 0xFFFF)
 * @return : CRC16 checksum
 */
uint16_t Get_CRC16_Check_Sum(const uint8_t *pchMessage, uint32_t dwLength, uint16_t wCRC)
{
	uint8_t ch_data;
	if (pchMessage == NULL)
		return 0xFFFF;
	while (dwLength--)
	{
		ch_data = *pchMessage++;
		(wCRC) =((uint16_t)(wCRC) >> 8) ^ W_CRC_TABLE[((uint16_t)(wCRC) ^ (uint16_t)(ch_data)) & 0x00ff];
	}
	return wCRC;
}

/**
 * @brief CRC16 Verify function
 * @param[in] pchMessage : Data to Verify,
 * @param[in] dwLength : Stream length = Data + checksum
 * @return : True or False (CRC Verify Result)
 */
uint32_t Verify_CRC16_Check_Sum(const uint8_t *pchMessage, uint32_t dwLength)
{
	uint16_t w_expected = 0;
	if ((pchMessage == NULL) || (dwLength <= 2))
		return false;
	w_expected = Get_CRC16_Check_Sum(pchMessage, dwLength - 2, CRC16_INIT); // dwLength - 2 ->dwLength - 4
	return ( (w_expected & 0xff) == pchMessage[dwLength - 2] &&( (w_expected >> 8) & 0xff ) == pchMessage[dwLength - 1] );
}

/**
 * @brief CRC16 Append function for different data structures
 * @param[in] pchMessage : Data to append CRC
 * @param[in] dwLength : Stream length = Data length + checksum
 * @param[in] dataType : Type of data (0 for SendPacketVision_s, 1 for OutputPCData_s)
 * @return : True or False (CRC Verify Result)
 */
void Append_CRC16_Check_Sum(void *pchMessage, uint32_t dwLength, int dataType)
{
	uint16_t w_crc = 0;

	if (pchMessage == NULL || dwLength <= 2)
	{
//		rt_kprintf("send error");
		return;
	}
	if (dataType == 0)
	{
		SendPacketVision_s *send_data = (SendPacketVision_s *)pchMessage;
		w_crc = Get_CRC16_Check_Sum((uint8_t *)(send_data), dwLength - 2, CRC16_INIT);
		send_data->checksum = w_crc;
//		rt_kprintf("checksum = %d\n", send_data->checksum);
	}
}


